package com.zte.cl.parser.utils;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.log4j.Logger;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.utils.FilePersistentBase;

import com.zte.cl.model.Img;
import com.zte.cl.utils.ConstantUtil;
import com.zte.cl.utils.DateUtil;
import com.zte.cl.utils.ImageBase64Util;
import com.zte.cl.utils.StringUtil;
import com.zte.cl.utils.UrlUtils;
import com.zte.cl.utils.UuidUtil;

public class ImgUtil {
	private final static Logger log = Logger.getLogger(ImgUtil.class);

	private static String URL_PATH_SEPERATOR = "/";
	private static String IMG_SUFFIX = ".jpg";

	public static ImgFull getNewImgSrc(String fileFolder, String imgSrc) {
		ImgFull imgFull = new ImgFull();
		try {
			// 图片存储物理路径
			String path = ConstantUtil.IMG_PATH;
			// 图片服务器
			String serverUrl = ConstantUtil.IMG_SERVER;
			Site site = Site.me().setDomain(UrlUtils.getDomain(imgSrc));
			// 图片下载工具
			ImageDownloader imageDownloader = new ImageDownloader();
			Page download = imageDownloader.download(new Request(imgSrc), site.toTask());
			// 不包含config.properties中img_path中的前缀路径
			String filePath = fileFolder + UuidUtil.getShortUuid() + "." + imageDownloader.getImageType();

			new FilePersistentBase().checkAndMakeParentDirecotry(path + filePath);
			boolean b = false;
			if (download != null) {
				b = ImageBase64Util.GenerateImage(path, filePath, download.getRawText());
			} else {
				log.error("图片下载失败，imgSrc=" + imgSrc);
				return null;
			}
			
			if (b) {
				imgFull.setNewSrc(serverUrl + filePath.replace(File.separator, URL_PATH_SEPERATOR));
				imgFull.setOriginalSrc(imgSrc);
				imgFull.setFilePath(filePath);
			}
			
		} catch (Exception e) {
			log.error("图片下载失败，imgSrc=" + imgSrc,e);
			return null;
		}
		return imgFull;
	}

	public static Img getImg(String newsId, String imgUrl, String newImgSrc, String filePath) {
		Img img = new Img();
		img.setId(UuidUtil.getShortUuid());
		img.setImgUrl(imgUrl);
		img.setNewsId(newsId);
		img.setNewImgUrl(newImgSrc);
		img.setPath(filePath);
		img.setInsertTime(DateUtil.getCurrentDate());
		return img;
	}

	public static String getImgFilePath(String channelId) {
		return DateUtil.getCurrentDateStr("yyyy" + File.separator + "MM" + File.separator + "dd") + File.separator + channelId
				+ File.separator;
	}

	public static String getImgFileName1(String channelId, String img_suffix) {
		return DateUtil.getCurrentDateStr("yyyy" + File.separator + "MM" + File.separator + "dd") + File.separator + channelId
				+ File.separator + UuidUtil.getShortUuid() + (StringUtil.isEmpty(img_suffix) ? IMG_SUFFIX : ("." + img_suffix));
	}

	public static boolean scaleRatio(String srcImageFile, String targetImage, int _width) {
		try {
			if (FileUtil.getImgType(srcImageFile).toLowerCase().equals("gif")) {
				// GIF不进行压缩处理
				return false;
			}
			BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
			int width = src.getWidth(); // 得到源图宽
			int height = src.getHeight(); // 得到源图长
			double scale = 0;
			if (width > _width) {
				scale = Double.valueOf(_width) / Double.valueOf(width);
				width = Double.valueOf(width * scale).intValue();
				height = Double.valueOf(height * scale).intValue();
				Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
				BufferedImage tag = new BufferedImage(width, height, BufferedImage.SCALE_SMOOTH);
				Graphics g = tag.getGraphics();
				g.drawImage(image, 0, 0, null); // 绘制缩小后的图
				g.dispose();
				ImageIO.write(tag, "JPEG", new File(targetImage));// 输出到文件流
			} else {
				Thumbnails.of(srcImageFile).scale(0.9f).toFile(targetImage);
			}
			return true;
		} catch (IOException e) {
			log.error(e);
			return false;
		}/*catch (Exception e) {
			log.error(e);
			return false;
		}*/
	}

	/**
	 * 在原图名字上加上后缀，生成缩略图地址的时候使用
	 * 
	 * @param imagePath
	 *            原图名称
	 * @return
	 * @date 2015-4-22
	 * @author Zjq
	 */
	public static String addSuffixToImage(String imagePath) {
		String thumbnailUrl = "";
		if (!com.zte.cl.utils.StringUtil.isEmpty(imagePath)) {
			thumbnailUrl = imagePath.substring(0, imagePath.lastIndexOf(".")) + "_tb" + "." + FileUtil.getImgType(imagePath);
		}
		return thumbnailUrl;
	}

	public static void main(String[] args) {
		scaleRatio("D://vivian.jpg", "D://vivian_780_1.jpg", 780);
		scaleRatio("D://vivian.jpg", "D://vivian_640_1.jpg", 640);
	}
}
